<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use app\erp\model\ErpSupplier;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 门店-供应商管理
 * @package app\erp\model
 */
class Supplierlogic{

    /**
     * 首页
     * @author  dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function index($user_id, $title){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' => $user_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($title != '') $map[] = ['title', 'like', '%'. $title .'%'];
			$list =  model('ErpSupplier', 'model') -> where($map) -> order('sort  ase,create_time desc')->paginate();//获取列表
			$rel_list = [];
            foreach($list as $key => $value){
				$rel_list[$key]['id'] 			    = (int)$value['id'];
				$rel_list[$key]['title'] 		    = (string)$value['title'];
				$rel_list[$key]['corporateName'] 	= (string)$value['corporate_name'];
				$rel_list[$key]['settlementCycle']  = (string)$value['settlement_cycle'];
				$rel_list[$key]['corporateAddress'] = (string)$value['corporate_address'];
				$rel_list[$key]['remarks'] 		    = (string)$value['remarks'];
				$rel_list[$key]['sort'] 		    = (int)$value['sort'];
				$rel_list[$key]['code'] 		    = (string)$value['code'];
				$rel_list[$key]['supplierType'] 	= (int)$value['supplier_type'];
				$rel_list[$key]['taxRate'] 			= (string)$value['tax_rate'];
				$rel_list[$key]['bankAccount'] 		= (string)$value['bank_account'];
				$rel_list[$key]['taxCode'] 			= (string)$value['tax_code'];
			}
            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加
     * @param title 	            string  供应商名称
     * @param code 		            string  供应商编码
     * @param settlement_cycle 		int     结算周日（天）
     * @param corporate_name 		string  公司名称
     * @param corporate_address 	string  公司地址
     * @param remarks 		        text    备注
     * @param sort 		            int     排序
	 * @param supplier_type 		int     1经销 2代销 3联营
     * @param tax_rate 				string     税率(%)
     * @param bank_account 			string  银行账户
     * @param tax_code 				string  税号
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function add($user_id, $title, $settlement_cycle, $corporate_name, $corporate_address, $remarks, $sort, $supplier_type, $tax_rate, $bank_account, $tax_code){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	        => $user_id,
				'title'             => $title,
                'corporate_name'    => $corporate_name,
                'settlement_cycle' 	=> $settlement_cycle,
                'corporate_address' => $corporate_address,
                'remarks' 	        => $remarks,
				'sort' 	            => $sort,
				'supplier_type' 	=> $supplier_type,
				'tax_rate' 	        => $tax_rate,
				'bank_account' 	    => $bank_account,
				'tax_code' 	    	=> $tax_code,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpSupplier') -> addData($title, $settlement_cycle, $corporate_name, $corporate_address, $remarks, $sort, $supplier_type, $tax_rate, $bank_account, $tax_code);//添加
            if($rel['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
			$supplier_id = $rel['data'];
			$code = sprintf("%04d", $supplier_id);
			
			$map = [];
			$map['id'] = $supplier_id;
			
			$data = [];
			$data['code'] = $code;
			$res = model('ErpSupplier') -> update($data, $map);
			if(!$res){
                DB::rollback();
                return array_out(-1005, 'error1');//code生成失败
            }
			
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 编辑
     * @param id 	            string  供应商名称
     * @param title 	            string  供应商名称
     * @param code 		            string  供应商编码
     * @param settlement_cycle 		int     结算周日（天）
     * @param corporate_name 		string  公司名称
     * @param corporate_address 	string  公司地址
     * @param remarks 		        text    备注
     * @param sort 		            int     排序
	 * @param supplier_type 		int     1经销 2代销 3联营
     * @param tax_rate 				int     税率(%)
     * @param bank_account 			string  银行账户
     * @param tax_code 				string  税号
     * @author dou<51779987@qq.com>
     * @return array_out(code, message, data)
     */
    public function edit($user_id,$id, $title, $settlement_cycle, $corporate_name, $corporate_address, $remarks, $sort, $supplier_type, $tax_rate, $bank_account, $tax_code){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	        => $user_id,
				'id' 		        => $id,
                'title'             => $title,
                'corporate_name'    => $corporate_name,
                'settlement_cycle' 	=> $settlement_cycle,
                'corporate_address' => $corporate_address,
                'remarks' 	        => $remarks,
                'sort' 	            => $sort,
				'supplier_type' 	=> $supplier_type,
				'tax_rate' 	        => $tax_rate,
				'bank_account' 	    => $bank_account,
				'tax_code' 	    	=> $tax_code,
            ];

            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			
			$rel = model('ErpSupplier') -> editData($id ,$title, $settlement_cycle, $corporate_name, $corporate_address, $remarks, $sort, $supplier_type, $tax_rate, $bank_account, $tax_code);
            if($rel['code'] == 200){
            }else{
                DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
            }
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 删除
     * @param int $id
     * @author dou<51779987@qq.com>
     * @return bool
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpSupplier') -> deleteData($id);
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
}